package com.authine.cloudpivot.sso.demo;

import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.web.api.domain.Constants;
import com.authine.cloudpivot.web.api.service.CheckUserService;
import com.authine.cloudpivot.web.sso.template.ResponseTypeEnum;
import com.authine.cloudpivot.web.sso.template.SimpleOAuth2Template;
import com.authine.cloudpivot.web.sso.template.SimpleTemplateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;



@Component
@Slf4j
public class WebSSOLogin extends SimpleOAuth2Template {

    @Autowired
    private CheckUserService checkUserService;

    WebSSOLogin() {
        super(SimpleTemplateConfig.builder()
                .requestMatcher(new AntPathRequestMatcher("/login/websso", HttpMethod.GET.name()))
                //验证通过后选择通过回调还是直接返回带token json串的方式
                .responseType(ResponseTypeEnum.JSON)
                //选择回调的话需要添加loginPassredirectUrl 会回调http://127.0.0.1/oauth地址然后把SSO的code传过去   如http://127.0.0.1/oauth?code=pOQrft    需要前端拿code获取SSO的token
                .mobile(false)       //是否手机登录
                .redirectClientID("api")    //云枢OAuth2登录的ClientId  具体体现在base_security_client表中
                .build());
    }

    /**
     * 调用websso获取accessToken
     * @param code
     * @return
     * @throws Exception
     */
    @Override
    public String getAccessToken(String code) throws Exception {
       String  token=checkUserService.getAccessToken(code, Constants.WEBSSO);
       return token;
    }

    /**
     * websso
     * @param code
     * @return
     * @throws Exception
     */
    @Override
    public String getSourceId(String code) throws Exception {
        String sourceId=checkUserService.getWebSourceId(code);
        return sourceId;
    }


    @Override
    public UserModel getUser(Object sourceId) {
        return this.dubboConfigService.getOrganizationFacade().getUser(String.valueOf(sourceId));
    }








}